package com.example.orderminiappapi.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.example.orderminiappapi.bean.*;
import com.example.orderminiappapi.service.*;
import com.example.orderminiappapi.tool.Createuuid;
import com.example.orderminiappapi.tool.GetTime;
import com.example.orderminiappapi.utils.webSocket.WebSocketServer;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private MealService mealService;

    /**
     * 生成订单/修改订单
     */
    @ResponseBody
    @RequestMapping(value = "/submitOrder", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response submitOrder(HttpServletRequest request, @RequestBody Order order) throws JsonProcessingException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String userId = verify.getClaim("openId").asString();

        User user = new User();
        user.setOpenid(userId);
        User findUser = userService.findAllUser(user);

        order.setUserName(findUser.getUserRealName());

        order.setUserId(userId);

        String orderId = order.getOrderId();

        Response response = null;

        if (orderId == null || orderId == "") {
            Createuuid createuuid = new Createuuid();
            String uuid = createuuid.getOrderIdByUUId();
            order.setOrderId(uuid);

            GetTime getTime = new GetTime();
            String createTime = getTime.getNowTime();
            order.setCreateTime(createTime);

            orderService.addOrder(order);

            List<OrderItem> orderItems = order.getOrderItems();

            for(int i = 0; i < orderItems.size(); i++){
                orderItems.get(i).setOrderId(uuid);
                orderService.addOrderItem(orderItems.get(i));
            }

            response = new Response("10000", "成功", uuid);

        } else {
            orderService.deleteOrderItemByOrderId(order);

            orderService.changeOrderAllPay(order);

            List<OrderItem> orderItems = order.getOrderItems();

            for(int i = 0; i < orderItems.size(); i++){
                orderItems.get(i).setOrderId(orderId);
                orderService.addOrderItem(orderItems.get(i));
            }

            response = new Response("10000", "成功", orderId);
        }

        return response;
    }

    /**
     * 下单
     */
    @ResponseBody
    @RequestMapping(value = "/perfectOrder", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response perfectOrder(@RequestBody Order order) throws IOException {

        GetTime getTime = new GetTime();
        String createTime = getTime.getNowTime();
        order.setCreateTime(createTime);

        orderService.perfectOrder(order);

        Shop shop = new Shop();
        shop.setShopId(order.getShopId());
        Shop shop1 = shopService.searchOneShop(shop);

        if(shop1.getAutoAcceptOrder()) {
            orderService.acceptOrder(order);
            WebSocketServer.sendInfo("为您自动接单啦，请及时处理", order.getShopId());
        } else {
            WebSocketServer.sendInfo("有新订单啦，请及时处理", order.getShopId());
        }

        Response response = new Response("10000", "成功", "成功");

        return response;
    }

    /**
     * 根据orderId获取订单
     */
    @ResponseBody
    @RequestMapping(value = "/getOrderByOrderId", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getOrderByOrderId(@RequestBody Order order) throws JsonProcessingException {

        Order returnOrder = orderService.getOrderByOrderId(order);

        returnOrder.setOrderItems(orderService.getOrderItemByOrderId(order));

        Response response = new Response("10000", "成功", returnOrder);

        return response;
    }

    /**
     * 获取未下单的订单
     */
    @ResponseBody
    @RequestMapping(value = "/getUnPerfectedOrder", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getUnPerfectedOrder(HttpServletRequest request, @RequestBody Order order) throws JsonProcessingException, ParseException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String userId = verify.getClaim("openId").asString();

        order.setUserId(userId);

        Order returnOrder = orderService.getUnPerfectedOrder(order);

        Response response = null;

        if(returnOrder != null) {
            GetTime getTime = new GetTime();
            if (getTime.ifOverDue(returnOrder.getCreateTime())) {
                orderService.deleteUnPerfectedOrder(returnOrder);
                orderService.deleteUnPerfectedOrderItem(returnOrder);
                response = new Response("10000", "成功", "无订单");
            } else {
                returnOrder.setOrderItems(orderService.getOrderItemByOrderId(returnOrder));
                response = new Response("10000", "成功", returnOrder);
            }
        } else {
            response = new Response("10000", "成功", "无订单");
        }
        return response;
    }

    /**
     * 获取未下单的订单
     */
    @ResponseBody
    @RequestMapping(value = "/getAllOrder", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getAllOrder(HttpServletRequest request) throws JsonProcessingException, ParseException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String userId = verify.getClaim("openId").asString();

        Order order = new Order();

        order.setUserId(userId);

        List<Order> orders = orderService.getAllOrder(order);


        if (orders.size() != 0) {
            for(int i = 0; i < orders.size(); i++){
                orders.get(i).setOrderItems(orderService.getOrderItemByOrderId(orders.get(i)));
                Shop shop = new Shop();
                shop.setShopId(orders.get(i).getShopId());
                orders.get(i).setShop(shopService.searchShopDetailByShopId(shop));
            }
        }

        Response response = new Response("10000", "成功", orders);

        return response;
    }

    /**
     * 根据orderId获取订单
     */
    @ResponseBody
    @RequestMapping(value = "/getOneOrder", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getOneOrder(@RequestBody Order order) throws JsonProcessingException, ParseException {

        Order returnOrder = orderService.getOneOrder(order);

        returnOrder.setOrderItems(orderService.getOrderItemByOrderId(returnOrder));
        Shop shop = new Shop();
        shop.setShopId(returnOrder.getShopId());
        returnOrder.setShop(shopService.searchShopDetailByShopId(shop));

        Response response = new Response("10000", "成功", returnOrder);

        return response;
    }

    /**
     * 打分
     */
    @ResponseBody
    @RequestMapping(value = "/doRate", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response doRate(@RequestBody Order order) {

        int flag = orderService.doRate(order);

        Response response;

        if(flag == 1) {
            response = new Response("10000", "成功", "成功");
        } else {
            response = new Response("10000", "失败", "失败");
        }

        return response;
    }

    /**
     * 写评价
     */
    @ResponseBody
    @RequestMapping(value = "/doEvaluate", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response doEvaluate(@RequestBody Order order) {

        int flag = orderService.doEvaluate(order);

        Response response;

        if(flag == 1) {
            response = new Response("10000", "成功", "成功");
        } else {
            response = new Response("10000", "失败", "失败");
        }

        return response;
    }


    /**
     * 后台管理接口
     */
    /**
     * 分页查询商店的订单列表
     */
    @ResponseBody
    @RequestMapping(value = "/shopOwnerSearchOrder", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response shopOwnerSearchOrder(HttpServletRequest request, @RequestBody SearchCondition searchCondition) {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String shopId = verify.getClaim("shopId").asString();

        searchCondition.setId(shopId);

        System.out.println(searchCondition);

        List<Order> orders = orderService.shopOwnerSearchOrder(searchCondition);

        searchCondition.setData(orders);
        searchCondition.setTotal(orderService.shopOwnerSearchOrderCount(searchCondition));

        Response response = new Response("10000", "成功", searchCondition);

        return response;
    }

    /**
     * 商家通过shopId获取未接受的订单
     */
    @ResponseBody
    @RequestMapping(value = "/getUnAcceptedOrder", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getUnAcceptedOrder(HttpServletRequest request) {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String shopId = verify.getClaim("shopId").asString();

        Order order = new Order();
        order.setShopId(shopId);

        List<Order> orders = orderService.getUnAcceptedOrder(order);

        HashMap map = new HashMap() {
            {
                put("unAcceptedOrder",orderService.getUnAcceptedOrder(order));
                put("unCompletedOrder",orderService.getUnCompletedOrder(order));
            }
        };

        Response response = new Response("10000", "成功", map);

        return response;
    }

    /**
     * 商家接受订单
     */
    @ResponseBody
    @RequestMapping(value = "/acceptOrder", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response acceptOrder(HttpServletRequest request, @RequestBody Order order) throws IOException {

        orderService.acceptOrder(order);

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String shopId = verify.getClaim("shopId").asString();

        WebSocketServer.sendInfo("成功接单", shopId);

        Response response = new Response("10000", "成功", "成功接单");

        return response;
    }

    /**
     * 商家或管理员取消订单
     */
    @ResponseBody
    @RequestMapping(value = "/cancelOrder", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response cancelOrder(HttpServletRequest request, @RequestBody Order order) throws IOException {

        orderService.cancelOrder(order);

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String shopId = verify.getClaim("shopId").asString();
        String userId = verify.getClaim("userId").asString();

        User user = new User();
        user.setUserId(userId);
        User performer = userService.findShopOwner(user);

        if (performer.getUserRole() == 2) {
            WebSocketServer.sendInfo("订单已取消，请及时与顾客联系", shopId);
        } else if (performer.getUserRole() == 3) {
            Notice notice = new Notice();

            Createuuid createuuid = new Createuuid();
            String uuid = createuuid.getOrderIdByUUId();
            notice.setNoticeId(uuid);

            GetTime getTime = new GetTime();
            String createTime = getTime.getNowTime();
            notice.setCreateTime(createTime);

            notice.setPerformerId(userId);
            notice.setPerformerName(performer.getUserName());

            Order order1 = orderService.getOneOrder(order);
            notice.setPassiveId(order1.getOrderId());
            notice.setPassiveName(order1.getUserName());
            notice.setShopId(order1.getShopId());
            notice.setType(6);

            noticeService.addNotice(notice);
            WebSocketServer.sendInfo("有新通知,请查看", order1.getShopId());
        }

        Response response = new Response("10000", "成功", "订单已取消，请及时与顾客联系");

        return response;
    }

    /**
     * 商家完成订单
     */
    @ResponseBody
    @RequestMapping(value = "/completeOrder", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response completeOrder(HttpServletRequest request, @RequestBody Order order) throws IOException {

        orderService.completeOrder(order);

        List<OrderItem> orderItems = orderService.getOrderItemByOrderId(order);

        for(OrderItem orderItem: orderItems) {
            mealService.completeOrder(orderItem);
        }


        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String shopId = verify.getClaim("shopId").asString();

        Shop shop = new Shop();
        shop.setShopId(shopId);

        shopService.completeOrder(shop);


        Response response = new Response("10000", "成功", "完成订单");

        return response;
    }

    /**
     * 获取每月的订单总数
     */
    @ResponseBody
    @RequestMapping(value = "/getOrderTrend", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getOrderTrend(HttpServletRequest request, @RequestBody Order order) throws IOException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String shopId = verify.getClaim("shopId").asString();

        order.setShopId(shopId);

        List<String> monthList = Stream.of("-01", "-02", "-03", "-04", "-05", "-06", "-07", "-08", "-09", "-10", "-11", "-12")
                .collect(Collectors.toList());

        List<Integer> monthOrderNumList = new ArrayList<>();

        String year = order.getCreateTime();

        for(int i = 0; i < monthList.size(); i++){
            order.setCreateTime(year + monthList.get(i));
            monthOrderNumList.add(orderService.getOrderTrend(order));
        }

        Response response = new Response("10000", "成功", monthOrderNumList);

        return response;
    }

    /**
     * 获取每月的销售额
     */
    @ResponseBody
    @RequestMapping(value = "/getSaleTrend", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getSaleTrend(HttpServletRequest request, @RequestBody Order order) throws IOException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String shopId = verify.getClaim("shopId").asString();

        order.setShopId(shopId);

        List<String> monthList = Stream.of("-01", "-02", "-03", "-04", "-05", "-06", "-07", "-08", "-09", "-10", "-11", "-12")
                .collect(Collectors.toList());

        List<Float> monthSaleNumList = new ArrayList<>();

        String year = order.getCreateTime();

        for(int i = 0; i < monthList.size(); i++){
            order.setCreateTime(year + monthList.get(i));
            if (orderService.getOrderTrend(order) != 0) {
                monthSaleNumList.add(orderService.getSaleTrend(order));
            } else {
                monthSaleNumList.add(0.0F);
            }
        }

        Response response = new Response("10000", "成功", monthSaleNumList);

        return response;
    }


    /**
     * 管理员接口
     * */

    /**
     * 管理员获取订单
     */
    @ResponseBody
    @RequestMapping(value = "/managerGetAllOrders", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response managerGetAllOrders(@RequestBody SearchCondition searchCondition) {

        List<Order> orders = orderService.managerSearchOrder(searchCondition);

        if (orders.size() != 0) {
            for(int i = 0; i < orders.size(); i++){
                orders.get(i).setOrderItems(orderService.getOrderItemByOrderId(orders.get(i)));
                Shop shop = new Shop();
                shop.setShopId(orders.get(i).getShopId());
                orders.get(i).setShop(shopService.searchShopDetailByShopId(shop));
            }
        }

        searchCondition.setData(orders);
        searchCondition.setTotal(orderService.managerSearchOrderCount(searchCondition));

        Response response = new Response("10000", "成功", searchCondition);

        return response;
    }
}
